import RankItem from "./RankItem";

const { ccclass, property } = cc._decorator;

@ccclass
export default class Rank extends cc.Component {

    @property(cc.Node)
    private content: cc.Node = null;

    @property(cc.Prefab)
    private itemPrefab: cc.Prefab = null;
    //加载动画
    // @property(cc.Node)
    // private loading: cc.Node = null;

    protected onLoad() {
        if (cc.sys.platform !== cc.sys.WECHAT_GAME_SUB) return;
        // 监听来自主域的消息
        wx.onMessage((msg: any) => this.onMessage(msg));
    }

    /**
     * 消息回调
     * @param msg 消息
     */
    private onMessage(msg: any) {
        switch (msg.event) {
            case 'setScore'://设置闯关模式玩家信息
                this.setScore(msg.score);
                break;
            case 'getRank'://设置闯关模式排行榜
                this.getRank();
                //                console.log("getRank has been called!");
                break;
            case 'setScore2'://设置闯关模式玩家信息
                this.setScore2(msg.score);
                break;
            case 'getRank2'://设置闯关模式排行榜
                this.getRank2();
                //                console.log("getRank has been called!");
                break;
        }
    }

    /**
     * 获取玩家闯关分数
     */
    private getScore(): Promise<number> {
        return new Promise(resolve => {
            // console.log('[getScore]');
            wx.getUserCloudStorage({
                keyList: ['score'],
                success: (res: UserGameData) => {
                    // console.log('[getScore]', 'success', res);
                    resolve(res.KVDataList[0] ? parseInt(res.KVDataList[0].value) : 0);
                },
                fail: () => {
                    // console.log('[getScore]', 'fail');
                    resolve(-1);
                }
            });
        });
    }

    /**
   * 获取玩家无尽模式分数
   */
    private getScore2(): Promise<number> {
        return new Promise(resolve => {
            // console.log('[getScore]');
            wx.getUserCloudStorage({
                keyList: ['score2'],
                success: (res: UserGameData) => {
                    // console.log('[getScore2]', 'success', res);
                    resolve(res.KVDataList[0] ? parseInt(res.KVDataList[0].value) : 0);
                },
                fail: () => {
                    // console.log('[getScore2]', 'fail');
                    resolve(-1);
                }
            });
        });
    }

    /**
     * 设置玩家分数
     * @param value 分数
     */
    private async setScore(value: number) {
        // console.log('[setScore]', value);
        let oldScore = await this.getScore();//获得原本的成绩
        if (oldScore === -1) return;
        if (value > oldScore) {//新数据
            wx.setUserCloudStorage({
                KVDataList: [{
                    key: 'score',
                    value: value.toString()
                }, {
                    key: 'time',
                    value: new Date().getTime().toString()
                }],//只需要写需要修改的KV列表
                success: () => {
                    // console.log('[setScore]', 'success');
                },
                fail: () => {
                    // console.log('[setScore]', 'fail');
                }
            });
        }
    }

    /**
     * 设置玩家无尽模式分数
     * @param value 分数
     */
    private async setScore2(value: number) {
        // console.log('[setScore2]', value);
        let oldScore = await this.getScore2();//获得原本的成绩
        if (oldScore === -1) return;
        if (value > oldScore) {//新数据
            wx.setUserCloudStorage({
                KVDataList: [{
                    key: 'score2',
                    value: value.toString()
                }, {
                    key: 'time2',
                    value: new Date().getTime().toString()
                }],//只需要写需要修改的KV列表
                success: () => {
                    // console.log('[setScore2]', 'success');
                },
                fail: () => {
                    // console.log('[setScore2]', 'fail');
                }
            });
        }
    }

    /**
     * 获取闯关模式排行榜
     */
    private async getRank() {
        // console.log('[getRank]');
        // 显示加载动画
        //    this.showLoading();
        // 调用微信的函数
        await new Promise(resolve => {
            wx.getFriendCloudStorage({
                keyList: ['score', 'time'],
                success: (res: any) => {
                    // console.log('[getRank]', 'success', res);
                    // 对数据进行排序
                    res.data.sort((a: UserGameData, b: UserGameData) => {
                        if (a.KVDataList.length === 0 && b.KVDataList.length === 0) { return 0 };
                        if (a.KVDataList.length === 0) return 1;
                        if (b.KVDataList.length === 0) return -1;
                        if ((parseInt(b.KVDataList[0].value) - parseInt(a.KVDataList[0].value)) == 0) {//如果两个人分数相同
                            if (a.KVDataList.length === 2 && b.KVDataList.length === 2) {//都有时间时，通关早的在前面
                                return parseInt(a.KVDataList[1].value) - parseInt(b.KVDataList[1].value);
                            }
                        }
                        return parseInt(b.KVDataList[0].value) - parseInt(a.KVDataList[0].value);//时间大的在后面
                    });
                    // 排序之后进行展示
                    this.updateRankList(res.data, 0);//传0表示分数种类是“关”
                    resolve();
                },
                fail: (res: any) => {
                    // console.log('[getRank]', 'fail');
                    resolve();
                }
            });
        });
        // 关闭加载动画
        //        this.hideLoading();
    }


    /**
     * 获取竞速模式排行榜
     */
    private async getRank2() {
        // console.log('[getRank2]');
        // 显示加载动画
        //    this.showLoading();
        // 调用微信的函数
        await new Promise(resolve => {
            wx.getFriendCloudStorage({
                keyList: ['score2', 'time2'],
                success: (res: any) => {
                    // console.log('[getRank2]', 'success', res);
                    // 对数据进行排序
                    res.data.sort((a: UserGameData, b: UserGameData) => {
                        if (a.KVDataList.length === 0 && b.KVDataList.length === 0) { return 0 };
                        if (a.KVDataList.length === 0) return 1;
                        if (b.KVDataList.length === 0) return -1;
                        if ((parseInt(b.KVDataList[0].value) - parseInt(a.KVDataList[0].value)) == 0) {//如果两个人分数相同
                            if (a.KVDataList.length === 2 && b.KVDataList.length === 2) {//都有时间时，通关早的在前面
                                return parseInt(a.KVDataList[1].value) - parseInt(b.KVDataList[1].value);
                            }
                        }
                        return parseInt(b.KVDataList[0].value) - parseInt(a.KVDataList[0].value);//时间大的在后面
                    });
                    // 排序之后进行展示
                    this.updateRankList(res.data, 1);//传1表示分数种类是“个”
                    resolve();
                },
                fail: (res: any) => {
                    // console.log('[getRank2]', 'fail');
                    resolve();
                }
            });
        });
        // 关闭加载动画
        //        this.hideLoading();
    }

    /**
     * 更新好友排行
     * @param data 数据
     */
    private updateRankList(data: UserGameData[], mode: number) {
        let count = Math.max(data.length, this.content.childrenCount);
        for (let i = 0; i < count; i++) {
            if (data[i] && this.content.children[i]) {
                // 已存在节点，更新并展示
                // console.log(i," node 存在，更新并展示。");
                this.content.children[i].active = true;
                this.content.children[i].getComponent(RankItem).set(i + 1, data[i], mode);
            }
            else if (data[i] && !this.content.children[i]) {
                // 节点不足，再实例化一个，更新信息
                // console.log(i," node 不存在，实例化创建。");
                let node = cc.instantiate(this.itemPrefab);
                node.setParent(this.content);
                this.content.children[i].active = true;
                this.content.children[i].getComponent(RankItem).set(i + 1, data[i], mode);
            }
            else {
                // 节点多了，关掉吧
                this.content.children[i].active = false;
            }
        }
    }

    /**
     * 显示加载动画
     */
    // private showLoading() {
    //     this.loading.active = true;
    // }

    // /**
    //  * 关闭加载动画
    //  */
    // private hideLoading() {
    //     this.loading.active = false;
    // }

}
